<?php
/**
 * Create by PhpStorm
 * Member Administrator
 * Date 2019/10/11
 * Time 11:02
 */

namespace app\admin\controller;

use app\admin\controller\Common;
use think\Db;
use think\Session;
use think\Request;
use app\api\model\User;
use app\api\model\MallDistribution;
use app\api\model\MallOrderFanli;

class Mall extends Common
{
    /**
     * 分类列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function typeid()
    {
        $parent_id = input('parent_id/d');
        $where = [];

        if ($parent_id !== null) {
            $where['parent_id'] = $parent_id;
        }

        $data = Db::name('mall_category')->where($where)->order('sort desc, id desc')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * 添加分类
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function typeidadd()
    {
        $typeiddb=Db::name('mall_category')->field('id, parent_id tid, name,image')->where(['is_hidden'=>0,'parent_id'=>0])->order('sort desc, id asc')->select();
        $this->assign('typeid',get_tree_option($typeiddb,0));

        $id = input("id/d");
        if (request()->isAjax()) {
            $post = input('post.');
            if (!$id) {   // 添加数据
                $typename = Db::name('mall_category')->where(['name' => $post['name']])->find();
                if ($typename) {
                    return ['err' => '栏目标题已存在'];
                }
                $db = Db::name('mall_category')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {      //修改数据
                $db = Db::name('mall_category')->where('id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('mall_category')->where(['id' => $id])->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function typeiddel()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                //$db = Db::name('mall_goods')->where('id', $id)->setField('delete_time', time());
                $db = Db::name('mall_category')->where('id', $id)->delete();
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    /**
     * 商品列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function goods()
    {
        $type = input('type');
        $name = input('name');
        $where = [];
        if ($type) {
            if ($type == 'id') {
                $where[$type] = $name;
            } else {
                $where[$type] = ['like', '%' . $name . '%'];
            }
        }
        $typeid = input('typeid');
        if ($typeid) {
            $where['cate_id'] = $typeid;
        }

        $whereStr = '';
        $class = input('class');
        if ($class) {
            $this->assign('class', $class);
            switch ($class) {
                case 1:
                    $whereStr = 'rec_sex <> "" or rec_age_min > 0 or rec_age_max > 0';
                    break;
                case 2:
                    $whereStr = 'fanli = 1';
                    break;
                
                default:
                    break;
            }
        }




        //$where['delete_time'] = ['EXP', 'IS NULL'];

        $data = Db::name('mall_goods')->where($where)->where($whereStr)->order('sort desc,id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    // 添加商品
    public function add()
    {
        $mychannel['id'] = 2;
        $this->assign('mychannel', $mychannel);

        $typeiddb = Db::name('mall_category')->order('sort desc,id asc')->select();
        $this->assign('typeid', $typeiddb);

        $id = input("id/d");

        if (request()->isAjax()) {
            $post = input('post.');
            $post['detail'] = Request::instance()->post('detail','','stripslashes');

            $time = time();
            if (!$post['cate_id']) {
                return ['err' => '请选择分类栏目'];
            }

            /*$res = Db::name('user')->where(['id' => $post['user_id']])->find();
            if (!$res) return ['err' => '用户不存在'];*/

            $post['update_time'] = $time; //更新时间

            // if (input('detail')) {
            //     $post['detail'] = html_entity_decode($post['detail']);
            // }
            //$post['price'] = $post['price'] * 100;
            // 处理图片集
            if ($post['images']) {
                $images = explode(',',$post['images']);

                $post['slider_image'] = json_encode($images);
            } else {
                $post['slider_image'] = '';
            }
            unset($post['images']);

            if (isset($post['skuname']) && sizeof($post['skuname'])) {
                $skuname = $post['skuname'];
                $skuprice = $post['skuprice'];
                $skustock = $post['skustock'];

                $skus = [];
                foreach ($skuname as $key => $value) {
                    if (!$value) continue;
                    if ($skuprice[$key] < 0) return ['err'=>'规格价格错误'];
                    if ($skustock[$key] < 0) return ['err'=>'规格库存错误'];
                    $skus[] = [
                        'name'=>$value,
                        'price'=>$skuprice[$key] ?: $post['price'],
                        'stock'=>$skustock[$key] ?: 0
                    ];
                }
                if (sizeof($skus)) {
                    $stockCount = array_sum(array_column($skus, 'stock'));
                    if ($stockCount) {
                        $post['stock'] = $stockCount;
                    }
                    $post['sku'] = implode(',', array_column($skus, 'name'));
                    $post['sku_price'] = implode(',', array_column($skus, 'price'));
                    $post['sku_stock'] = implode(',', array_column($skus, 'stock'));
                }
            } else {
                $post['sku'] = '';
                $post['sku_price'] = '';
                $post['sku_stock'] = '';
            }
            unset($post['skuname'], $post['skuprice'], $post['skustock']);

            if (!$id) {   // 添加数据
                $titledb = Db::name('mall_goods')->where(['name' => $post['name']])->find();
                if ($titledb) {
                    return ['err' => '名称已存在'];
                }

                if (!$post['stock']) return ['err' => '新增商品库存不能为空'];

                $post['create_time'] = $time;
                $post['xuni_sales'] = rand(100, 500);
                $db = Db::name('mall_goods')->insertGetId($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {      //修改数据
                if (!$post['stock']) {
                    $post['is_hidden'] = 1;
                }

                $db = Db::name('mall_goods')->where('id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('mall_goods')->where('id', $id)->find();
                $name['images'] = $name['slider_image'];
                $skus = [];

                if ($name['sku']) {
                    $skuname = explode(',', $name['sku']);
                    $skuprice = explode(',', $name['sku_price']);
                    $skustock = explode(',', $name['sku_stock']);
                    foreach ($skuname as $key => $value) {
                        $skus[] = [
                            'name'=>$value,
                            'price'=>$skuprice[$key]??0,
                            'stock'=>$skustock[$key]??0
                        ];
                    }

                }
                $name['skus'] = $skus;
                $this->assign('name', $name);
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除商品
    public function del()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                //$db = Db::name('mall_goods')->where('id', $id)->setField('delete_time', time());
                $db = Db::name('mall_goods')->where('id', $id)->delete();
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    /**
     * 订单管理
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function order()
    {
        $type = input('type');
        $name = input('name');
        $where = [];
        if ($type && $name) {
            $where['t1.' . $type] = $name;
        }
    
        $types = input('types') ?: 1;
        $where['t1.types'] = $types;

        // 处理过期订单
        // Db::name('mall_order')->where(['status' => 0, 'expire_time' => ['elt', time()]])->setField('status', -3);

        $data = Db::name('mall_order t1')
                    ->field('t1.*,t2.name,t2.phone, t4.name goods_name')
                    ->join('user t2', 't2.id = t1.uid')
                    ->join('mall_order_item t3', 't3.order_id = t1.id', 'left')
                    ->join('mall_goods t4', 't4.id = t3.goods_id', 'left')
                    ->where($where)
                    ->order('t1.id desc')
                    ->paginate(_getCachePages(), false, ['query' => request()->param()]);


        $page = $data->render();


        $unsend[] = Db::name('mall_order')->where(['status'=>1, 'address'=>['<>', ''], 'types'=>1])->count();
        $unsend[] = Db::name('mall_order')->where(['status'=>1, 'address'=>['<>', ''], 'types'=>2])->count();
        $this->assign('unsend', $unsend);
        

        $this->assign('data', $data);
        $this->assign('page', $page);
        
        $this->assign('types', $types);
        
        return $this->fetch();
    }

    /**
     * 订单详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function dingdancode()
    {
        $id = input('id/d');
        $name = Db::name('mall_order')->find($id);

        $name['address'] = json_decode($name['address'], true);

        $shop = Db::name('mall_order_item t1')
            ->join('mall_goods t2', 't2.id = t1.goods_id')
            ->where(['t1.order_id' => $id])
            ->field('t1.goods_id,t1.sku,t2.name,t1.price,t1.num,t2.url,t2.image')
            ->select();

        /*$shop = Db::name('shoplists')->find($name['shopid']);*/
        $member = _user($name['uid']);
        
        $to_user = $name['to_user'] ? _user($name['to_user']) : [];
        
        $this->assign('name', $name);
        $this->assign('shop', $shop);
        $this->assign('member', $member);
        $this->assign('to_user', $to_user);
        return $this->fetch();
    }

    /**
     * 订单发货
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function dingdanadd()
    {
        $id = input('id/d');
        $post = input('post.');
        $order = Db::name('mall_order')
                ->where(['id' => $id])
                ->find();
        if (!$order) {
            exit(json_encode(['err' => '订单不存在']));
        }
        switch ((int)$post['status']) {
            case 2:
                if ($order['status'] != 1) {
                    exit(json_encode(['err' => '订单未支付']));
                }
                if (!isset($post['tracking_number']) || !$post['tracking_number']) {
                    exit(json_encode(['err' => '请先填写快递单号']));
                }
                $res = Db::name('mall_order')
                    ->where(['id' => $id])
                    ->update(['status' => 2, 'tracking_name' => $post['tracking_name'], 'tracking_number' => $post['tracking_number']]);

                if ($res) {
                    exit(json_encode(['ret' => '操作成功']));
                } else {
                    exit(json_encode(['err' => '操作失败']));
                }
                break;
            case 3:
                if ($order['status'] != 2) {
                    exit(json_encode(['err' => '订单未发货']));
                }
                $res = Db::name('mall_order')
                    ->where(['id' => $id])
                    ->update(['status' => 3]);
                if ($res) {
                    $rate = 5;
                    $fencheng_content = '购物商品结算';
                    User::fencheng($order['uid'], 0, $order['total'] * $rate, 'mall', $fencheng_content);
                    MallDistribution::setStatus($order['id'], 1);
                    MallOrderFanli::setStatus($order['id'], 1);
                    exit(json_encode(['ret' => '操作成功']));
                } else {
                    exit(json_encode(['err' => '操作失败']));
                }
                break;
            case -2:
                $res = Db::name('mall_order')
                    ->where(['id' => $id])
                    ->update(['status' => -2]);
                MallDistribution::setStatus($order['id'], -1);
                MallOrderFanli::setStatus($order['id'], -1);
                exit(json_encode(['ret' => '操作成功']));
                break;
            case -4:
                $res = Db::name('mall_order')
                    ->where(['id' => $id])
                    ->update(['status' => -4]);
                MallDistribution::setStatus($order['id'], -1);
                MallOrderFanli::setStatus($order['id'], -1);
                exit(json_encode(['ret' => '操作成功']));
                break;
            default:
                exit(json_encode(['err' => '暂不支持该操作']));
        }
    }


    public function question()
    {
        $search_name = input('search_name');
        $where = [];
        if ($search_name) {
            $where['title|content'] = ['like', '%' . $search_name . '%'];
        }
        $category = input('category');
        if ($category) {
            $where['category'] = $category;
        }
        $category = Db::name('mall_question_category')->order('sort desc,id desc')->column('id,title');

        $data = Db::name('mall_question')
                    ->where($where)
                    ->order('sort desc,id desc')
                    ->paginate(_getCachePages(), false, ['query' => request()->param()])
                    ->each(function ($item) use ($category)
                    {
                        $item['category_name'] = $category[$item['category']] ?? '';
                        return $item;
                    });
        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function questionwatch($id)
    {
        $data = Db::name('mall_question')->field('id,title,content')->find($id);
        if (!$data) {
            exit('内容不存在');
        }
        echo $data['content'];
    }
    public function addquestion()
    {

        $category = Db::name('mall_question_category')->order('sort desc,id asc')->select();
        $this->assign('category', $category);

        $id = input("id/d");

        if (request()->isAjax()) {
            $post = input('post.');

            $time = time();
            if (!$post['category']) {
                return ['err' => '请选择分类'];
            }

            $post['update_time'] = $time;
            if (!$id) {   // 添加数据
                $titledb = Db::name('mall_question')->where(['title' => $post['title']])->find();
                if ($titledb) {
                    return ['err' => '标题已存在'];
                }
                $post['create_time'] = $time;

                $db = Db::name('mall_question')->insertGetId($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $db = Db::name('mall_question')->where('id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('mall_question')->where('id', $id)->find();
                $this->assign('name', $name);
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delquestion()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('mall_question')->where('id', $id)->delete();
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    public function questionCategory()
    {
        $data = Db::name('mall_question_category')->order('sort desc, id desc')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function addquestionCategory()
    {
        $id = input("id/d");
        if (request()->isAjax()) {
            $post = input('post.');
            $post['update_time'] = time();
            if (!$id) {
                $typename = Db::name('mall_question_category')->where(['title' => $post['title']])->find();
                if ($typename) {
                    return ['err' => '栏目标题已存在'];
                }
                $post['create_time'] = $post['update_time'];
                $db = Db::name('mall_question_category')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $db = Db::name('mall_question_category')->where('id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('mall_question_category')->where(['id' => $id])->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delquestionCategory()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('mall_question_category')->where('id', $id)->delete();
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
    public function distribution()
    {
        $type = input('type');
        $name = input('name');
        $where = [];
        if ($type && $name) {
            if ($type == 'uid') {
                $where['t1.user_id|t1.one_uid|t1.two_uid|t1.three_uid'] = $name;
            } else {
                $where['t1.' . $type] = $name;
            }
        }
    
        $status = input('status');
        if ($status || $status === '0') {
            $where['t1.status'] = $status;
            $this->assign('status', $status);
        }

        $data = Db::name('mall_distribution t1')
                ->join('user t2', 't2.id = t1.user_id', 'left')
                ->join('user t3', 't3.id = t1.one_uid', 'left')
                ->join('user t4', 't4.id = t1.two_uid', 'left')
                ->join('user t5', 't5.id = t1.three_uid', 'left')
                ->where($where)
                ->field('t1.*, t2.name as username2, t3.name as username3, t4.name as username4, t4.name as username4, t5.name as username5')
                ->order('t1.id desc')
                ->paginate(_getCachePages(), false, ['query' => request()->param()]);


        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);
        
        
        return $this->fetch();
    }
    public function rebate()
    {
        $type = input('type');
        $name = input('name');
        $where = [];
        if ($type && $name) {
            $where[$type] = $name;
        }
        $this->assign('type', $type);
    
        $state = input('state');
        if ($state || $state === '0') {
            $where['state'] = $state;
            $this->assign('state', $state);
        }

        $data = Db::name('mall_order_fanli')
                ->where($where)
                ->order('id desc')
                ->paginate(_getCachePages(), false, ['query' => request()->param()]);


        $page = $data->render();

        $data = $data->all();
        $users = Db::name('user')->where(['id'=>['in', array_column($data, 'user_id')]])->column('name','id');
        foreach ($data as &$value) {
            $value['username'] = $users[$value['user_id']]??'';
        }

        $this->assign('data', $data);
        $this->assign('page', $page);
        
        
        return $this->fetch();
    }
    public function rebate_records()
    {
        $type = input('type');
        $name = input('name');
        $where = [];
        if ($type && $name) {
            $where[$type] = $name;
        }
        $this->assign('type', $type);

        $data = Db::name('mall_order_fanli_records')
                ->alias('r')
                ->join('mall_order_fanli f', 'r.mall_order_fanli_id=f.id')
                ->where($where)
                ->field('r.*, f.order_id,f.user_id')
                ->order('r.id desc')
                ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $page = $data->render();

        $data = $data->all();
        $users = Db::name('user')->where(['id'=>['in', array_column($data, 'user_id')]])->column('name','id');
        foreach ($data as &$value) {
            $value['username'] = $users[$value['user_id']]??'';
        }

        $this->assign('data', $data);
        $this->assign('page', $page);
        
        return $this->fetch();
    }

    public function rebate_accelerate()
    {
        $type = input('type');
        $name = input('name');
        $where = [];
        if ($type && $name) {
            $where[$type] = $name;
        }
        $this->assign('type', $type);

        $data = Db::name('mall_order_fanli_help')
                ->alias('r')
                ->join('mall_order_fanli f', 'r.mall_order_fanli_id=f.id')
                ->where($where)
                ->field('r.*, f.order_id,f.user_id as to_user_id')
                ->order('r.id desc')
                ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $page = $data->render();

        $data = $data->all();
        $users = Db::name('user')->where(['id'=>['in', array_merge(array_column($data, 'user_id'), array_column($data, 'to_user_id'))]])->column('name','id');
        foreach ($data as &$value) {
            $value['username'] = $users[$value['user_id']]??'';
            $value['to_username'] = $users[$value['to_user_id']]??'';
        }

        $this->assign('data', $data);
        $this->assign('page', $page);
        
        return $this->fetch();
    }
}
